import { Component, OnInit, Injector, ViewChild, Output, EventEmitter } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { ModalDirective } from 'ngx-bootstrap';
import {
    StockZT_RoomServiceProxy,
    Stock_RoomEditDto,
    ComboboxItemDto,
    EditDtoExtensionsItem
} from '@shared/service-proxies/stock-service-proxies';
import { finalize } from 'rxjs/operators';

@Component({
    selector: 'createOrEditRoomModal',
    templateUrl: './create-or-edit-room-modal.component.html'
})
export class CreateOrEditRoomModalComponent extends AppComponentBase implements OnInit {
    constructor(injector: Injector, private _stockZT_RoomServiceProxy: StockZT_RoomServiceProxy) {
        super(injector);
    }
    @ViewChild('createOrEditModal') modal: ModalDirective;

    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

    active = false;
    saving = false;
    editDto: Stock_RoomEditDto;
    extensions: Array<EditDtoExtensionsItem>;
    optionAll;
    deptlist: ComboboxItemDto[] = [];

    ngOnInit(): void {}
    show(id?: string): void {
        this.active = true;
        this._stockZT_RoomServiceProxy.getRoomEditExtensionById(id).subscribe(result => {
            this.optionAll = {
                f_DepartmentOptions: result.selectDepartmentOptions,
                f_WarehouseTypeOptions: result.selectWarehouseTypeOptions,
                f_StockTypeOptions: result.selectStockTypeOptions,
                f_StockLevelOptions: result.selectStockLevelOptions
            };
            this.editDto = result.stock_RoomEditDto;
            this.extensions = result.items;
            this.modal.show();
        });
    }

    save(): void {
        this.saving = true;
        let input = new Stock_RoomEditDto();
        input = this.editDto;

        this._stockZT_RoomServiceProxy
            .createOrUpdateRoom(input)
            .pipe(
                finalize(() => {
                    this.saving = false;
                })
            )
            .subscribe(() => {
                this.notify.info(this.l('SavedSuccessfully'));
                this.close();
                this.modalSave.emit(null);
            });
    }

    close(): void {
        this.active = false;
        this.modal.hide();
    }
}
